/*
 * @Author: AskMeWhy
 * @Date: 2020-12-01 18:05:43
 * @Last Modified by: AskMeWhy
 * @Last Modified time: 2021-01-14 14:22:21
 */

import Vue from "vue";
import Component from "vue-class-component";
// eslint-disable-next-line @typescript-eslint/no-var-requires
const CosAuth: any = require("./cos-auth");
// const CosAuth = require("./cos-auth.min.ts");
// 获取临时密钥
let stsCache: any;
const getCredentials = (initAuth: any): Promise<any> => {
    return new Promise((resolve, reject) => {
        if (stsCache && Date.now() / 1000 + 30 < stsCache.expiredTime) {
            return resolve(stsCache.credentials);
        }
        if (initAuth) {
            initAuth()
                .then((r: any) => {
                    stsCache = r;
                    return resolve(stsCache.credentials);
                })
                .catch((err: any) => {
                    console.log(err);
                    return reject(err);
                    // wx.showModal({ title: "错误提示", content: "临时密钥获取失败", showCancel: false });
                });
        } else {
            return reject({
                title: "错误提示",
                content: "临时密钥获取失败"
            });
            // wx.showModal({ title: "错误提示", content: "临时密钥获取失败", showCancel: false });
        }
    });
};

// 计算签名
const getAuthorization = (options: any): Promise<any> => {
    return new Promise((resolve, reject) => {
        getCredentials(options.initAuth)
            .then((credentials: any) => {
                return resolve({
                    XCosSecurityToken: credentials.sessionToken,
                    Authorization: CosAuth({
                        SecretId: credentials.tmpSecretId,
                        SecretKey: credentials.tmpSecretKey,
                        Method: options.Method,
                        Pathname: options.Pathname
                    })
                });
            })
            .catch((err: any) => {
                return reject(err);
            });
    });
};
// You can declare mixins as the same style as components.
@Component
export default class AuthMixin extends Vue {
    getCredentials(params: any) {
        return new Promise(async(resolve, reject) => {
            const response = await this.$server.cosAuth(params);
            const { data } = response;
            if (data.code !== 200) {
                reject(data);
            }
            resolve(data.data);
        });
    }

    getAuthorization(options: any) {
        return getAuthorization({
            initAuth: this.getCredentials,
            ...options
        });
    };
}
